<script setup>
import DatasourceEdit from '@/views/beetlsql/datasource/DatasourceEdit.vue';
import { reactive, ref } from 'vue';
import { VDataTableServer } from 'vuetify/labs/VDataTable';


//查询条件
const dsBeanName = ref()
const dsName = ref()
const disabled = ref()
const jdbcUrl = ref()

// 表头
const headers = [
  {
    title: 'Bean名称',
    key: 'dsBeanName',
  },
  {
    title: '数据源中文名称',
    key: 'dsName',
  },
  {
    title: '数据库驱动路径',
    key: 'driverClassName',
  },
  {
    title: '数据库连接路径',
    key: 'jdbcUrl',
  },
  {
    title: '用户名',
    key: 'username',
  },
  {
    title: '是否禁用',
    key: 'disabled',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

// 分页查询
const totalPage = ref(1) //总页数
const totalRows = ref(0) //总记录数
const list = ref([]) // 当前分页数据
const loadings = ref(false)

const fetchList = async (msg) => {
  loadings.value = true
  const res = await $ivyApi.post(API_URLS.dbDatasourcePage,{
    dsBeanName: dsBeanName.value,
    dsName: dsName.value,
    jdbcUrl: jdbcUrl.value,
    disabled: disabled.value,
    options: options.value,
  })
  
  const data = res.data
  list.value = data.list
  totalPage.value = data.totalPage
  totalRows.value = data.totalRow
  options.value.page = data.page
  loadings.value = false

  if(typeof msg === 'string'){
    res.message = msg
    showMsg(res)
  }
}

watchEffect(fetchList)
// 监听 options 对象的变化，并在变化时调用 fetchList 方法
watch(options, async () => { await fetchList() }, { deep: true })

// 删除操作
const deleteId = ref('')
const deleteName = ref('')
const deleteVisible = ref(false)

const deleteOper = row => {
  deleteVisible.value = true
  deleteId.value = row.id
  deleteName.value = row.dsName
}

const deleteAgreeOper = async (id) => {
  const res = await $ivyApi.post(API_URLS.dbDatasourceDelete,{
    id: deleteId.value,
  })

  showMsg(res)
  fetchList()
  deleteVisible.value = false
  deleteId.value = ''
}

// 新增操作&编辑操作
const editKey = ref(1)
const operType = ref(0) // 操作类型：0新增，1更新
const currRow = ref({})
const addVisible = ref(false)

const addOper = () => {
  editKey.value++
  operType.value = 0
  currRow.value = {}
  addVisible.value = true
}

const addData = async (data) => {
  const res = await $ivyApi.post(API_URLS.dbDatasourceAdd,data)
  showMsg(res)
  fetchList()
}

const updateOper = row => {
  editKey.value++
  operType.value = 1
  currRow.value = row
  addVisible.value = true
}

const updateData = async (data) => {
  const res = await $ivyApi.post(API_URLS.dbDatasourceUpdate,data)
  showMsg(res)
  fetchList()
}

// 回调信息
const snackbar = reactive(API_URLS.resultMsg)

const showMsg = res => {
  $resultMsg.show(res,snackbar)
}

// 初始化
onMounted(() => {
  
})

const disabledOption = [
  { color: 'error', title: '禁用', value: 1 },
  { color: 'success', title: '启用', value: 0 },
]

const resolveStatusVariant = status => {
  return disabledOption.filter(obj => obj.value == status)[0]
}
</script>

<template>
  <section>
    <VSnackbar
      v-model="snackbar.msgVisible"
      location="top"
      :color="snackbar.msgColor"
    >
      {{ snackbar.msgContent }}
    </VSnackbar>
    <VRow>
      <VCol cols="12">
        <VCard>
          <!-- 👉 Filters -->
          <VCardText>
            <VRow>
              <VCol
                cols="12"
                sm="3"
              >
                <VTextField
                  v-model="dsBeanName"
                  label="Bean名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VTextField
                  v-model="dsName"
                  label="数据源中文名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VTextField
                  v-model="jdbcUrl"
                  label="数据库连接路径"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="3"
              >
                <VAutocomplete
                  v-model="disabled"
                  label="是否禁用"
                  :items="disabledOption"
                  clearable
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="inline-size: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                :loading="loadings"
                :disabled="loadings"
                size="38"
                @click="fetchList('刷新成功')"
              >
                <VIcon
                  icon="tabler-refresh"
                  size="22"
                />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  刷新
                </VTooltip>
              </VBtn>
              <VBtn
                prepend-icon="tabler-plus"
                @click="addOper"
              >
                新增数据源
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <!-- SECTION datatable -->
          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <template #item.dsBeanName="{ item }">
              <span class="font-weight-medium">{{ item.dsBeanName }}</span>
            </template>

            <template #item.dsName="{ item }">
              <span class="font-weight-medium">{{ item.dsName }}</span>
            </template>

            <template #item.dsDesc="{ item }">
              <span class="font-weight-medium">{{ item.dsDesc }}</span>
            </template>

            <template #item.driverClassName="{ item }">
              <span class="font-weight-medium">{{ item.driverClassName }}</span>
            </template>

            <template #item.jdbcUrl="{ item }">
              <span class="font-weight-medium">{{ item.jdbcUrl }}</span>
            </template>

            <template #item.username="{ item }">
              <span class="font-weight-medium">{{ item.username }}</span>
            </template>

            <template #item.disabled="{ item }">
              <VChip
                :color="resolveStatusVariant(item.disabled).color"
                class="font-weight-medium"
                size="small"
              >
                {{ resolveStatusVariant(item.disabled).title }}
              </VChip>
            </template>

            <template #item.actions="{ item }">
              <IconBtn @click="deleteOper(item)">
                <VIcon icon="tabler-trash" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  删除
                </VTooltip>
              </IconBtn>

              <IconBtn @click="updateOper(item)">
                <VIcon icon="tabler-edit" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  编辑
                </VTooltip>
              </IconBtn>
            </template>

            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">&nbsp;{{ totalRows }}&nbsp;</span>条记录
                </p>
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <!-- 👉 类 -->
        
        <DatasourceEdit
          v-if="addVisible"
          :key="'cmp-edit-'+editKey"
          v-model:isDrawerOpen="addVisible"
          :oper-type="operType"
          :curr-row="currRow"
          @add-data="addData"
          @update-data="updateData"
        /> 
       
        <!-- 删除确认 -->
        <VDialog
          v-model="deleteVisible"
          width="300"
        >
          <DialogCloseBtn @click="deleteVisible = !deleteVisible" />
          <VCard title="提示">
            <VCardText> 是否删除数据源[{{ deleteName }}]？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="deleteVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeOper">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>
      </vcol>
    </vrow>
  </section>
</template>



<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}
</style>
